package com.cindata

import com.cindata.dictionary.EvaluateDict
import com.cindata.dictionary.ExecStatusDict
import com.cindata.dictionary.ImportFileTypeDict
import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['isAuthenticated()'])
@Transactional
class VehicleImportBatchController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    def springSecurityService
    def evaluateService

    def index(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        def order = params["order"]
        def sort = params["sort"]
        String sql = " from VehicleImportBatch e where 1=1"
//        String sql1 = " from VehicleImport e where 1=1"
        def user = User.findById(springSecurityService.principal.id)
        def accountSql = Account.FilterAccountSql(user)
        if (accountSql)
        {
            sql += " and e.createBy.account.id in ${accountSql}"
//            sql1 += " and e.createBy.account.id in ${accountSql}"
        }
        if (order && sort)
        {
            sql += " order by e.${sort} ${order}"
        }
        else
        {
            sql += " order by e.createdDate desc "
        }
        println "sql:  "+sql
        def vehicleImportBatchList = VehicleImportBatch.executeQuery(sql, [max: params.max ?: 10, offset: params.offset ?: 0])
//        def vehicleImportList = VehicleImport.executeQuery(sql1, [max: params.max ?: 10, offset: params.offset ?: 0])

        respond vehicleImportBatchList, model: [vehicleImportBatchList: vehicleImportBatchList, vehicleImportBatchCount: VehicleImportBatch.count()]
    }

    @Transactional
    def searchVehicle()
    {
        def order = params["order"]
        def sort = params["sort"]
        def batchs = params["batchs"]
        //批次号
        def createBy = params["createBy"]
        //导入经手人
        def status = params['status']
        //导入状态
        def importFileType = params["importFileType"]
        //导入文件类型
        def evaluateType = params['evaluateType']
        //处理方式
        def startDate = params["startDate"]
        //开始时间
        def endDate = params["endDate"]
        //结束时间
        def sqlParam = [:]
        String sql = "from VehicleImportBatch e where 1=1"
        def user = User.findById(springSecurityService.principal.id)
        def accountSql = Account.FilterAccountSql(user)
        if (accountSql)
        {
            sql += " and e.createBy.account.id in ${accountSql}"
        }
        if (batchs)
        {
            sql += " and e.batchNumber like '%${batchs}%'"
        }
        if (status)
        {
            sql += " and e.status.name = '${status}'"
        }
        if (evaluateType)
        {
            sql += " and e.evaluateType.id= '${evaluateType}'"
        }
        if (startDate && endDate)
        {
            //中文日期转换
            sqlParam.startDate = DateUtil.GetDateBeginByDateStr(startDate.toString())
            sqlParam.endDate = DateUtil.GetNextDateBeginByDateStr(endDate.toString())
            sql += "and e.createdDate >= :startDate and e.createdDate  < :endDate "
        }
        if (createBy)
        {
            sql += "and e.createBy.id = '${createBy}'"
        }
        if (importFileType)
        {
            sql += "and e.importFileType.id = '${importFileType}'"
        }
        //查询总数
        String countSql = "select count(e.id) " + sql

//        if (order && sort)
//        {
//            sql += " order by e.${sort} ${order}"
//        }
//        else
//        {
            sql += "order by e.createdDate desc "
//        }
        println(sql)
        //执行查询方法
        def vehicleImportBatchList = VehicleImportBatch.executeQuery(sql, sqlParam, [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = VehicleImportBatch.executeQuery(countSql, sqlParam)

        if (vehicleImportBatchList != null)
        {
            respond VehicleImportBatch, model: [vehicleImportBatchList: vehicleImportBatchList, vehicleImportBatchCount: count[0], params: params], view: 'index'
        }
        else
        {
            respond VehicleImportBatch, view: 'index'
        }

    }

    @Transactional
    def csvImport()
    {
        /**
         * 读取文件*/
        def file = request.getFile('myFile')
        def fileCharset = FileUtil.GetFileCharset(file.getInputStream())
        def iftCode = params["importFileType"]
        def evaluateType = params["evaluateType"]

        //将文件传给对应类,读取文件
        def importer
        if (iftCode == "Estate")
        {
            importer = new VehicleCSVImporter()
        }
        else if (iftCode == "Repayment")
        {
            importer = new RepaymentCSVImporter()
        }
        def vehicleMapList = importer.read(file.getInputStream(), fileCharset)
        //获取集合
        def estateNum = vehicleMapList.size()

        def batch = params["batch"]
        def createBy = User.findByUsername(sec.loggedInUserInfo(field: "username"))
        def currentDate = new Date()
        def importFileType = ImportFileTypeDict.findByCode(iftCode)
        def evaluateTypeTemp
        if (evaluateType == "1")
        {
            evaluateTypeTemp = EvaluateDict.AUTOMATIC()
        }
        if (evaluateType == "7")
        {
            evaluateTypeTemp = EvaluateDict.ARTIFICIAL()
        }
        if (evaluateType == "8")
        {
            evaluateTypeTemp = EvaluateDict.AUTOANDARTIFICIAL()
        }

        /**
         * 加入批次信息*/
        Map param = [batchNumber: batch,
            importFileType: importFileType,
            estateNum: estateNum,
            matchNum: 0,
            status: ExecStatusDict.EXECUTING(),
            createBy: createBy,
            isDeleted: 0,
            evaluateType: evaluateTypeTemp]

        def newImportBatch = new VehicleImportBatch(param)

        //将批次信息加入批次表中
        if (!newImportBatch.save())
        {
            println "VehicleImportBatch not saved, errors = ${newImportBatch.errors}"
            respond VehicleImportBatch, model: ["message": "导入失败", "success": false], view: "message"
        }

        println '批次ID: [' + newImportBatch?.id + "]"

        /**
         * 遍历存入excel里的数据*/
        Thread.start {
            evaluateService.batchInsertsVehicle(vehicleMapList, newImportBatch, currentDate)
            //            if (iftCode == 'Estate')
            //            {
            //                // evaluateType  1 : 自动， 7： 人工 8：自动加人工
            //                evaluateService.evaluateBatch(newImportBatch.getId(), evaluateType?.toInteger())
            //            }
        }
        respond VehicleImportBatch, model: ["success": true, "key": newImportBatch.id], view: "message"
        return
    }

    def getProgress(Long progressKey)
    {
        def progress = evaluateService.getProgress(progressKey)
        render([progress: progress] as grails.converters.JSON)
    }

    def show(VehicleImportBatch vehicleImportBatch)
    {
        respond vehicleImportBatch
    }

    def create()
    {
        respond new VehicleImportBatch(params)
    }

    @Transactional
    def save(VehicleImportBatch vehicleImportBatch)
    {
        if (vehicleImportBatch == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (vehicleImportBatch.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond vehicleImportBatch.errors, view: 'create'
            return
        }

        vehicleImportBatch.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'vehicleImportBatch.label', default: 'VehicleImportBatch'), vehicleImportBatch.id])
                redirect vehicleImportBatch
            }
            '*' { respond vehicleImportBatch, [status: CREATED] }
        }
    }

    def edit(VehicleImportBatch vehicleImportBatch)
    {
        respond vehicleImportBatch
    }

    @Transactional
    def update(VehicleImportBatch vehicleImportBatch)
    {
        if (vehicleImportBatch == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (vehicleImportBatch.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond vehicleImportBatch.errors, view: 'edit'
            return
        }

        vehicleImportBatch.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'vehicleImportBatch.label', default: 'VehicleImportBatch'), vehicleImportBatch.id])
                redirect vehicleImportBatch
            }
            '*' { respond vehicleImportBatch, [status: OK] }
        }
    }

    @Transactional
    def delete(VehicleImportBatch vehicleImportBatch)
    {

        if (vehicleImportBatch == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        vehicleImportBatch.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'vehicleImportBatch.label', default: 'VehicleImportBatch'), vehicleImportBatch.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'vehicleImportBatch.label', default: 'VehicleImportBatch'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }
}
